﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WROA.Models.ViewModels;
using WROA.Models.Entitys;
using WROA.Models.Services;
using WROA.Models.IServices;

namespace WROA.Controllers
{
    public class CarController : Controller
    {
        //
        // GET: /Car/

        public ActionResult ApplyCar()
        {
            ApplyCarView model = new ApplyCarView();
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ApplyCar(FormCollection form)
        {
            IUserService us = new UserService();
            IFlowService fs = new FlowService();
            ICarService cs = new CarService();

            if (!cs.CarIsFree(Convert.ToInt32(form["CarId"]), Convert.ToDateTime(form["StartTime"]), Convert.ToDateTime(form["EndTime"])))
            {
                ModelState.AddModelError("CarIsNotFree", "该时间段车辆正在使用中，请重新选择其他时间");
                return View();
            }

            ApplyCar applyCar = new ApplyCar();
            applyCar.Ac_time = DateTime.Now;
            applyCar.User = us.GetUser(User.Identity.Name);
            applyCar.Flow = fs.GetFlow(form["FlowName"]);
            applyCar.Procedure = fs.GetFirstProcedure(applyCar.Flow);
            applyCar.Ac_htmldata = form["Html"];
            applyCar.Ac_state = "未结束";
            applyCar.Ac_isagree = null;
            //applyCar.U_name = null;
            cs.Save(applyCar);

            ApplyCarData applyCarData = new ApplyCarData();
            applyCarData.Acd_address = form["Address"];
            applyCarData.Acd_starttime = Convert.ToDateTime(form["StartTime"]);
            applyCarData.Acd_starttime = Convert.ToDateTime(form["EndTime"]);
            applyCarData.Acd_purpose = form["Purpose"];
            applyCarData.Applycar = applyCar;
            applyCarData.Car = cs.GetCar(Convert.ToInt32(form["CarId"]));//保存用车车辆
            cs.Save(applyCarData);

            List<string> passengerName = new List<string>();
            cs.SavePassage(applyCarData, passengerName);//保存用车人员

            return View();
        }

    }
}
